package com.ai.web.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;


public class HttpUtil {

	private static Logger logger = Logger.getLogger(HttpUtil.class);
	
	public static HttpResponse httpRequest(String url, String method, Map<String, String> headers, String body) {
//		logger.info("[ConferenceEsb.httpRequest] url = ["+url+"], " +
//				"method = ["+method+"], headers = ["+headers+"], body = ["+body+"]");
		HttpURLConnection connection = null;
		BufferedReader reader = null;
		StringBuffer result = new StringBuffer("");
		HttpResponse response = new HttpResponse();
		try {
			URL postUrl = new URL(url);
			connection = (HttpURLConnection) postUrl.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod(method);
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			if(headers != null && headers.size() != 0) {
				for (Entry<String, String> entry : headers.entrySet()) {
					connection.addRequestProperty(entry.getKey(), entry.getValue());
				}
			}
			connection.connect();
			if(body != null && !body.equals("")) {
				OutputStream os=connection.getOutputStream(); 
		        try {
					os.write(body.getBytes());
				} catch (Exception e) {
					logger.error("[ConferenceEsb.httpRequest] error", e);
				} finally {
					if(os != null) {
				        os.flush();   
				        os.close(); 
					}
				}
			}
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line = "";
			while ((line = reader.readLine()) != null) {
				result.append(line);
			}
			
			response.setResponseCode(connection.getResponseCode());
			response.setBody(result.toString());
			response.setHeaders(connection.getHeaderFields());
		} catch (Exception e) {
			logger.error("[ConferenceEsb.httpRequest] error", e);
		} finally {
			try {
				if(reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				logger.error("[ConferenceEsb.httpRequest] error", e);
			}
			if(connection != null) {
				connection.disconnect();
			}
		}
		logger.info("[ConferenceEsb.httpRequest] response = ["+response+"]");
		return response;
	 }
	
	
	
}

